package com.mokairui.share_model_nolock;

import lombok.Data;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @Description 原子类(AtomicInteger, AtomicLong...)的实现: 通过 Unsafe
 * @Author Mokairui
 * @Since 2021/10/5
 */
public class UnsafeAccessor {
    static Unsafe unsafe;

    static {
        try {
            // theUnsafe是private, 所以只能使用反射进行获取
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            unsafe = (Unsafe) theUnsafe.get(null);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    static Unsafe getUnsafe() {
        return unsafe;
    }

    /**
     * theUnsafe 可以使用原子性的赋值 原子类底层就是通过此进行实现的
     * @param args
     */
    public static void main(String[] args) throws Exception {
        Unsafe unsafe = UnsafeAccessor.getUnsafe();
        Field id = Student.class.getDeclaredField("id");
        Field name = Student.class.getDeclaredField("name");

        // 获取成员变量的偏移量
        long idOffset = UnsafeAccessor.unsafe.objectFieldOffset(id);
        long nameOffset = UnsafeAccessor.unsafe.objectFieldOffset(name);

        Student student = new Student();
        // 使用 cas 方法替换成员变量的值 参数:(对象, 成员变量偏移量, 旧值, 新值)
        UnsafeAccessor.unsafe.compareAndSwapInt(student, idOffset, 0, 20); // 修改成功返回ture
        UnsafeAccessor.unsafe.compareAndSwapObject(student, nameOffset, null, "张三"); // 修改成功返回true

        System.out.println(student);
    }
}

@Data
class Student {
    volatile int id;
    volatile String name;
}


